// 定义常量，promise的三种状态
const PENDING = "pending"
const FULFILLED = "fulfilled"
const REJECTED = "rejected"

// 定义一个promise类
class MPromise {
    // 首先有三个值
    // 状态
    _status = PENDING
    // 两个待执行任务的数组
    FULFILLED_CALLBACKS = []
    REJECTED_CALLBACKS = []

    // 构造函数
    constructor(fn) {
        // 初始化值
        this.value = null
        this.reason = null
        this._status = PENDING

        // 立即执行fn，注意要用trycatch
        try {
            // 注意要用bind绑定自身
            fn(this.resolve.bind(this), this.reject.bind(this))
        } catch (error) {
            this.reject(error)
        }
    }

    // 设置status的获取值对象
    get status() {
        return this._status
    }

    set status(value) {
        this._status = value
        switch (this._status) {
            case FULFILLED:
                this.FULFILLED_CALLBACKS.forEach((fn) => fn())
                break
            case REJECTED:
                this.REJECTED_CALLBACKS.forEach((fn) => fn())
                break
            default:
                break
        }
    }

    resolve(value) {
        if (this.status !== PENDING) {
            this.status = FULFILLED
            this.value = value
        }
    }

    reject(reason) {
        if (this.status !== PENDING) {
            this.status = REJECTED
            this.reason = reason
        }
    }

    // 定义then方法
    then(onFulfilled, onRejected) {
        // 接收两个参数
        const realOnFulfilled = this.isFunction(onFulfilled)
            ? onFulfilled
            : (value) => value
        const realOnRejected = this.isFunction(onRejected)
            ? onRejected
            : (reason) => {
                  throw reason
              }

        // 定义返回值
        const promise2 = new Promise((resolve, reject) => {
            
        })
    }

    // 定义检测是否是函数
    isFunction(fn) {
        return typeof fn === "function"
    }

    // 对then中的结果进行判定
    resolvePromise() {}
}